package Sunny.Sun.controller;

import Sunny.Sun.controller.utils.R;
import Sunny.Sun.domain.Book;
import Sunny.Sun.service.BookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public R getAll() {
        return new R(true, bookService.list());
    }

    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        return new R(bookService.save(book));
    }

    @PutMapping
    public R update(@RequestBody Book book) {
        return new R(bookService.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(bookService.removeById(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, bookService.getById(id));
    }

    @GetMapping("{current}/{pageSize}")
    public R getPage(@PathVariable int current, @PathVariable int pageSize, Book book) {
        IPage<Book> page = bookService.getPage(current, pageSize, book);
        //如果当前页码值超过了页码总值，则重新查询最大页码值，并显示其数据
        if(current > page.getPages()){
            page = bookService.getPage((int)page.getPages(), pageSize, book);
        }

        return new R(true,page);
    }
}
